﻿using System;
using System.Web;
using System.Web.UI.WebControls;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;

namespace AspDIY.Net.Common
{
    /// <summary>
    /// upfile操作类
    /// </summary>
    public class Upfile : System.Web.UI.Page
    {
        /// <summary>
        /// 错误输出
        /// </summary>
        public string msg;

        #region 上传路径
        string _upfilepath = "";
        /// <summary>
        /// 上传路径
        /// </summary>
        public string upfilepath
        {
            get { return _upfilepath; }
            set { _upfilepath = value; }
        }
        #endregion

        #region 自定义文件名
        string _upfilename;
        /// <summary>
        /// 自定义文件名
        /// </summary>
        public string upfilename
        {
            get { return _upfilename; }
            set { _upfilename = value; }
        }
        #endregion

        #region 最大上传文件大小1024K
        int _maxsize = 1024;
        /// <summary>
        /// 最大上传文件大小1024K
        /// </summary>
        public int maxsize
        {
            get { return _maxsize; }
            set { _maxsize = value; }
        }
        #endregion

        #region 允许上传类型
        /// <summary>
        /// 允许上传类型
        /// </summary>
        string _filetype = ".jpg,.gif,.bmp,.png,.rar,.txt,.doc";
        /// <summary>
        /// 允许上传类型
        /// </summary>
        public string filetype
        {
            get { return _filetype; }
            set { _filetype = value; }
        }
        #endregion

        #region 水印图片路径
        string _waterfilepath;
        /// <summary>
        /// 水印图片路径
        /// </summary>
        public string waterfilepath
        {
            get { return _waterfilepath; }
            set { _waterfilepath = value; }
        }
        #endregion

        #region 水印文字内容
        string _waterstr = "版权所有";
        /// <summary>
        /// 水印文字内容
        /// </summary>
        public string waterstr
        {
            get { return _waterstr; }
            set { _waterstr = value; }
        }
        #endregion

        #region 水印文字颜色
        /// <summary>
        /// 水印文字颜色
        /// </summary>
        string _watercolor = "#000000";
        public string watercolor
        {
            get { return _watercolor; }
            set { _watercolor = value; }
        }
        #endregion

        #region 水印背景颜色
        string _waterbgcolor = "#000000";
        /// <summary>
        /// 水印背景颜色
        /// </summary>
        public string waterbgcolor
        {
            get { return _waterbgcolor; }
            set { _waterbgcolor = value; }
        }
        #endregion

        #region 是否开启文字水印

        bool _openimgwater = false;
        /// <summary>
        /// 是否开启文字水印
        /// </summary>
        public bool openimgwater
        {
            get { return _openimgwater; }
            set { _openimgwater = value; }
        }
        #endregion

        #region 是否开启图片水印
        string _openstrwater;
        /// <summary>
        /// 是否开启图片水印
        /// </summary>
        public string openstrwater
        {
            get { return _openstrwater; }
            set { _openstrwater = value; }
        }
        #endregion

        #region 是否开启缩略图功能
        /// <summary>
        /// 是否开启缩略图功能
        /// </summary>
        string _opensmallpic;
        public string opensmallpic
        {
            get { return _opensmallpic; }
            set { _opensmallpic = value; }
        }
        #endregion

        #region 缩略图路径
        string _smallpicpath;
        /// <summary>
        /// 缩略图路径
        /// </summary>
        public string smallpicpath
        {
            get { return _smallpicpath; }
            set { _smallpicpath = Server.MapPath(value); }
        }
        #endregion


        #region 检测文件是否合法
        /// <summary>
        /// 检测上传文件是否合法
        /// </summary>
        /// <param name="fileExtends">文件后缀名</param>
        /// <returns></returns>
        public bool CheckFileExtends(string fileExtends)
        {
            return Utils.InArray(fileExtends, filetype, ",", true);
        }
        #endregion


        #region 保存文件
        /// <summary>
        /// 保存文件(服务器控件)
        /// </summary>
        /// <param name="myFileUpload">上传控件</param>
        /// <returns></returns>
        public string FileSave(FileUpload myFileUpload)
        {
            string fileExtends = "";
            string fileName = myFileUpload.FileName;

            if (myFileUpload.HasFile)
            {
                //取得文件后缀
                fileExtends = Utils.FileExtName(fileName);
                if (this.CheckFileExtends(fileExtends))
                {
                    if (myFileUpload.PostedFile.ContentLength <= maxsize * 1024)
                    {
                        try
                        {
                            Utils.FolderCreate(upfilepath);
                            if (upfilename == null) upfilename = DateRndName(false) + fileExtends;
                            myFileUpload.SaveAs(upfilepath + upfilename);
                            fileName = upfilename;
                            this.msg = "上传成功！";
                        }
                        catch (Exception ee)
                        {
                            throw new Exception(ee.ToString());
                        }
                    }
                    else
                    {
                        this.msg = "上传内容为" + (myFileUpload.PostedFile.ContentLength / 1024) + "KB，超过了" + maxsize + "KB！";
                        fileName = "";
                    }
                }
                else
                {
                    this.msg = "文件格式不正确！只允许上传" + filetype + "格式";
                    fileName = "";
                }

            }
            else
            {
                this.msg = "上传内容为空！";
                fileName = "";
            }
            return fileName;
        }

        /// <summary>
        /// 保存文件(客户端控件)
        /// </summary>
        /// <param name="PostFile">上传控件</param>
        /// <returns></returns>
        public string FileSave(HttpPostedFile PostFile)
        {
            string fileExtends = "";
            string fileName = System.IO.Path.GetFileName(PostFile.FileName);

            if (fileName != null)
            {
                //取得文件后缀
                fileExtends = Utils.FileExtName(fileName);
                if (this.CheckFileExtends(fileExtends))
                {
                    if (PostFile.ContentLength <= maxsize * 1024)
                    {
                        try
                        {
                            if (upfilename == null) upfilename = DateRndName(false) + fileExtends;
                            Utils.FolderCreate(upfilepath);
                            PostFile.SaveAs(upfilepath + upfilename);
                            fileName = upfilename;
                            this.msg = "上传成功！";
                        }
                        catch (Exception ee)
                        {
                            throw new Exception(ee.ToString());
                        }
                    }
                    else
                    {
                        this.msg = "上传内容为" + (PostFile.ContentLength / 1024) + "KB，超过了" + maxsize + "KB！";
                        fileName = "";
                    }
                }
                else
                {
                    this.msg = "文件格式不正确！只允许上传" + filetype + "格式";
                    fileName = "";
                }

            }
            else
            {
                this.msg = "上传内容为空！";
                fileName = "";
            }
            return fileName;
        }
        #endregion


        #region 保存文件流
        /// <summary>
        /// 保存文件流
        /// </summary>
        /// <param name="fs">流文件</param>
        /// <returns></returns>
        public string ServerFileSave(byte[] fs)
        {
            string fileName = upfilename;
            if (fileName != null)
            {
                if (fs.Length <= maxsize * 1024)
                {
                    try
                    {
                        Utils.FolderCreate(upfilepath);
                        //定义并实例化一个内存流，以存放提交上来的字节数组。
                        MemoryStream m = new MemoryStream(fs);

                        //定义实际文件对象，保存上载的文件。

                        FileStream f = new FileStream(upfilepath + fileName, FileMode.Create);

                        //把内内存里的数据写入物理文件

                        m.WriteTo(f);

                        m.Close();

                        f.Close();

                        f = null;

                        m = null;
                        fileName = upfilename;
                        this.msg = "上传成功！";
                    }
                    catch (Exception ex)
                    {

                        throw new Exception(ex.ToString());

                    }
                }
                else
                {
                    fileName = "";
                    this.msg = "上传内容为" + (fs.Length / 1024) + "KB，超过了" + maxsize + "KB！";
                }
            }
            else
            {
                fileName = "";
                this.msg = "该方式上传必须指定文件！";
            }
            return fileName;
        }
        #endregion

        #region 加入文字水印

        /// <summary>
        /// 加入文字水印
        /// </summary>
        /// <param name="fileName">文件名称路径(全路径)</param>
        /// <param name="text">文件</param>

        public void AddTextToImg(string fileName, string text)
        {
            if (!File.Exists(fileName))
            {
                throw new FileNotFoundException("文件不存在");
            }
            if (text == string.Empty)
            {
                return;
            }
            //判断文件类型是否为图像类型
            if (Path.GetExtension(fileName).ToLower() == ".jpg")
            {
                System.Drawing.Image image = System.Drawing.Image.FromFile(fileName);
                Bitmap bitmap = new Bitmap(image, image.Width, image.Height);
                Graphics g = Graphics.FromImage(bitmap);
                float fontSize = 12.0f;//字体大小
                float textWidth = text.Length * fontSize;//文本的长度
                //下面定义一个矩形区域,以后在这个矩形里面画上白底黑字
                float rectX = 10;
                float rectY = 10;
                float rectWidth = text.Length * (fontSize + 8);
                float rectHeight = fontSize + 8;
                //声明矩形域
                RectangleF textArea = new RectangleF(rectX, rectY, rectWidth, rectHeight);
                Font font = new Font("宋体", fontSize);//定义字体
                Brush whiteBrush = new SolidBrush(Color.Blue);//白笔刷,画文字用
                Brush blackBrush = new SolidBrush(Color.Black);//黑笔刷，画背景用
                g.FillRectangle(blackBrush, rectX, rectY, rectWidth, rectHeight);
                g.DrawString(text, font, whiteBrush, textArea);
                // MemoryStream ms = new MemoryStream();
                bitmap.Save(smallpicpath + Path.GetFileName(fileName));
                //输出处理后的图像，这里为了演示方便，我将图片显示在页面中了
                //Response.Clear();
                //Response.ContentType = "image/jpeg";
                //Response.BinaryWrite(ms.ToArray());
                g.Dispose();
                bitmap.Dispose();
                image.Dispose();
                this.msg = "非jpg格式图片，生成失败！" + Path.GetFileName(fileName);
            }
            else
            {
                this.msg = "非jpg格式图片，生成失败！" + Path.GetDirectoryName(fileName);
            }
        }
        #endregion

        #region 日期随机函数
        /// <summary>
        /// 日期随机函数
        /// </summary>
        /// <param name="IsShort">是否只需要HHmmss</param>
        /// <returns></returns>
        public string DateRndName(bool IsShort)
        {
            string s = TypeConvert.StandardDateTimeToStr(DateTime.Now.ToString(), "yyyyMMddHHmmss");
            if (IsShort) s = TypeConvert.StandardDateTimeToStr(DateTime.Now.ToString(), "HHmmss");
            Random ra = new Random();
            s += ra.Next(100, 999).ToString();
            return s;
        }
        #endregion
    }
}